import os
import configparser
from common.consts import CONFIG_PATH

class Config(object):
    """封装获取conf文件类"""
    def __init__(self, filename="config.ini"):
        self.cf = configparser.ConfigParser()
        self.log_path = os.path.join(CONFIG_PATH, filename)
        self.cf.read(self.log_path)

    def get_conf(self, section, option):
        return self.cf.get(section, option)

    def set_conf(self, section, option, value):
        self.cf.set(section, option, value)
        with open(self.log_path, 'w+') as f:
            return self.cf.write(f)

    def add_section(self, section):
        self.cf.add_section(section)
        with open(self.log_path, 'w+') as f:
            return self.cf.write(f)

    def get_runtime(self, option):
        return self.get_conf("runtime", option)

    def get_server(self, option):
        return self.get_conf("server", option)

    def get_db_test(self, option):
        return self.get_conf("db_test", option)

    def get_email(self, option):
        return self.get_conf("email", option)

if __name__ == '__main__':
    # 验证是否成功运行
    cf = Config()    # 实例化Config类
    print(cf.get_conf('server', 'test'))    # 获取config.ini配置， 参数：扇区和扇区下的键
    cf.set_conf('server', 'xxxx', 'gggg')   # 设置config.ini配置， 添加参数：扇区和扇区下的键以及键的值
    cf.add_section("shanqu")                # 仅添加config.ini配置中的扇区
    print(cf.get_runtime("timeout"))        # 获取config.ini配置中指定的runtime扇区中键的值
    print(cf.get_server("test"))            # 获取config.ini配置中指定的server扇区中键的值
    print(cf.get_db_test("host"))           # 获取config.ini配置中指定的db_test扇区中键的值
    print(cf.get_email("user"))             # 获取config.ini配置中指定的email扇区中键的值
